package me.jzn.alib.utils;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;

import androidx.core.content.ContextCompat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import me.jzn.alib.ALib;
import me.jzn.core.exceptions.ShouldNotRunHereException;

/**
 * @author xqs
 * 用来简化一些Context的操作
 */
public class CtxUtil {
    private static final Logger log = LoggerFactory.getLogger(CtxUtil.class);

    public static ContentResolver getContentResolver() {
        return ALib.app().getContentResolver();
    }

    public static Configuration getAppConfiguation() {
        return ALib.app().getResources().getConfiguration();
    }

    public static final <T> T getSystemService(Class<T> serviceClass) {
        return ContextCompat.getSystemService(ALib.app(), serviceClass);
    }

    /**
     * 高版本记得manifest中添加<query><package /></query>,否则，返回值是false
     */
    public static final boolean bindServiceByClzName(Context ctx, String svcPkg, String svcClzName, ServiceConnection cbk) {
        Intent intent = new Intent();
        // intent.setPackage("com.jzn.keybox.net");
        intent.setComponent(new ComponentName(svcPkg, svcClzName));
        try {
            return ctx.bindService(intent, cbk, Context.BIND_AUTO_CREATE);
        } catch (SecurityException e) {
            throw new ShouldNotRunHereException("两个应用签名不一致/或者本应用没有申请权限!", e);
        }
    }

    /**
     * 高版本记得manifest中添加<query><package /></query>,否则，返回值是false
     */
    public static final boolean bindServiceByAction(Context ctx, String svcPkg, String action, ServiceConnection cbk) {
        Intent intent = new Intent();
        intent.setPackage(svcPkg);
        intent.setAction(action);
        try {
            return ctx.bindService(intent, cbk, Context.BIND_AUTO_CREATE);
        } catch (SecurityException e) {
            throw new ShouldNotRunHereException("两个应用签名不一致/或者本应用没有申请权限!", e);
        }
    }
}
